<template>
  <div id="com-list">
    <!-- 顶部搜索新增操作 -->
    <div class="">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input
            placeholder="请输入模板信息，搜索模板"
            v-model="searchValue"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getComponentTemplate(searchValue)"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="componentAdd"> 新增 </el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 中部组件模板列表 -->
    <el-table
      :data="componentList"
      @row-click="tableRowClick"
      highlight-current-row
      height="50%"
    >
      <el-table-column label="排序" prop="componentSort" />
      <el-table-column label="组件名称" prop="componentName" />
      <el-table-column label="组件类型" prop="componentType">
        <template slot-scope="{ row }">
          {{ ["单栏行", "双栏行", "多行列表"][row["componentType"]] }}
        </template>
      </el-table-column>
      <el-table-column label="组件描述" prop="componentDesc" />
      <el-table-column label="操作" width="200">
        <template slot-scope="{ row, $index }">
          <a @click.stop="componentPreview(row)">预览</a>
          <a
            class="ml-10"
            @click.stop="componentUpdate(row, 'visibleUpdatedElement', $index)"
          >
            编辑元素
          </a>
          <a
            class="ml-10"
            @click.stop="componentUpdate(row, 'visibleComponentDialog', $index)"
            >编辑</a
          >
          <a class="ml-10" @click.stop="componentDelete(row)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <!-- 底部编辑元素 -->
    <div class="mt-10" v-show="visibleUpdatedElement">
      <div v-if="templateData.componentType == 2">
        <span>列表行数：</span>
        <el-input type="number" v-model="templateData.rowsLimit" />
      </div>
      <el-table :data="templateData.element.column">
        <!-- 元素名称 -->
        <el-table-column label="元素名称" prop="label">
          <template slot-scope="{ row }">
            <el-input type="text" v-model="row['label']"></el-input>
          </template>
        </el-table-column>
        <!-- 元素类型 -->
        <el-table-column label="元素类型">
          <template slot-scope="{ row, $index }">
            <el-select v-model="row.valueType" @change="elementChange(row)">
              <el-option :value="'text'" label="文本" />
              <el-option :value="'radio'" label="单选" />
              <el-option :value="'checkbox'" label="多选" />
              <el-option :value="'fromToDate'" label="起止日期" />
            </el-select>
            <span>
              <el-button
                v-if="
                  !row.visibleNewOptionInput &&
                  (row.valueType == 'radio' || row.valueType == 'checkbox')
                "
                @click="showOptionInput(row, 'option_' + $index)"
                class="button-new-tag"
                >+新增选项</el-button
              >
              <el-input
                :ref="'option_' + $index"
                class="input-new-tag"
                v-model="newOptionLabel"
                v-if="row.visibleNewOptionInput"
                @blur="newOption(row)"
                @keyup.enter.native="newOption(row)"
              ></el-input>
            </span>
            <div v-if="row.valueType == 'radio' || row.valueType == 'checkbox'">
              <el-tag
                v-for="(options, i) in row.options"
                :key="i"
                closable
                @close="deleteOption(row.options, i)"
              >
                {{ options.label }}
              </el-tag>
              <span></span>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column width="150" v-if="templateData.componentType == 2">
          <div slot="header">
            操作
            <a class="ml-10" @click="addCol">增加列</a>
          </div>
          <template
            slot-scope="{ $index }"
            v-if="templateData.element.column.length > 1"
          >
            <a class="ml-10" aria-disabled @click="deleteCol($index)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="text-align-center pt-10 pm-10">
        <el-button round @click="saveTemplate" type="success">确认</el-button>
        <el-button round @click="visibleUpdatedElement = false">取消</el-button>
      </div>
    </div>
    <!-- dialog部分 -->
    <el-dialog
      :title="{ true: '编辑', false: '新增' }[isUpdate]"
      :visible.sync="visibleComponentDialog"
    >
      <el-form label-width="80px">
        <el-form-item label="排序">
          <el-input
            type="number"
            v-model="templateData.componentSort"
          ></el-input>
        </el-form-item>
        <el-form-item label="组件名称">
          <el-input v-model="templateData.componentName"></el-input>
        </el-form-item>
        <el-form-item label="组件描述">
          <el-input v-model="templateData.componentDesc"></el-input>
        </el-form-item>
        <el-form-item label="组件类型">
          <el-select
            v-model="templateData.componentType"
            @change="componentTypeChange"
          >
            <el-option :value="'0'" label="单栏行" />
            <el-option :value="'1'" label="双栏行" />
            <el-option :value="'2'" label="多行列表" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visibleComponentDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTemplate">保存</el-button>
      </div>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog :title="'预览'" :visible.sync="visibleComponentPreview">
      <form-table ref="formTable" />
    </el-dialog>
  </div>
</template>
<script>
class comColumn {
  valueType = "text";
  label = "";
  defalutValue = "";
  options = [];
  optionValueCode = 1; //选项绑定value避免重复
  visibleNewOptionInput = false;
}
class comTemplateData {
  componentName = "新增组件名称"; //组件名称
  componentType = "0"; //组件类型 0单栏行 1双栏行 2多行列表
  componentDesc = ""; //描述
  componentSort = 0; //排序
  rowsLimit = 1; //2多行列表 行数
  element = {
    column: [new comColumn()],
  };
  constructor(obj = {}) {
    obj = JSON.parse(JSON.stringify(obj));
    typeof obj.element == "string" && (obj.element = JSON.parse(obj.element));
    Object.assign(this, obj);
  }
}
export default {
  name: "comList",
  data() {
    return {
      searchValue: "", //
      templateData: new comTemplateData(),
      visibleComponentDialog: false,
      componentList: [],
      isUpdate: false, //是否编辑
      visibleComponentPreview: false,
      newOptionLabel: "",
      visibleUpdatedElement: false,
    };
  },
  methods: {
    /*------模板增删改-----*/
    // 预览
    componentPreview(val) {
      this.visibleComponentPreview = true;
      this.$nextTick((_) => {
        this.$refs.formTable.updatedData();
        this.$refs.formTable.addRow(val);
      });
    },
    // 新增组件模板-弹框显示
    componentAdd() {
      this.isUpdate = false;
      this.templateData = new comTemplateData();
      this.visibleComponentDialog = true;
    },
    //编辑组件模板-弹框显示
    componentUpdate(val, key) {
      this.isUpdate = true;
      this.templateData = new comTemplateData(val);
      this[key] = true;
    },
    //删除模板
    async componentDelete(item) {
      this.$confirm(`是否删除 ${item.componentName} ?`).then(async () => {
        await this.$http({
          data: {
            componentId: item.componentId,
          },
          url: "form/component-template/delete",
        });
        this.getComponentTemplate();
      });
    },
    //保存模板
    async saveTemplate() {
      this.templateData.element = JSON.stringify(this.templateData.element);
      if (this.isUpdate) {
        await this.$http({
          data: this.templateData,
          url: "form/component-template/update",
        });
      } else {
        await this.$http({
          data: this.templateData,
          url: "form/component-template/insert",
        });
      }
      this.visibleComponentDialog = false;
      this.visibleUpdatedElement = false;
      this.getComponentTemplate();
    },
    /*------END-----*/

    //多列模板-删除列
    deleteCol(index) {
      this.templateData.element.column.splice(index, 1);
    },
    //多列模板-新增列
    addCol() {
      this.templateData.element.column.push(new comColumn());
    },
    //新增选项
    newOption(row) {
      if (this.newOptionLabel) {
        row.optionValueCode = ++row.optionValueCode;
        row.options.push({
          label: this.newOptionLabel,
          value: row.optionValueCode,
        });
        this.newOptionLabel = null;
      }
      row.visibleNewOptionInput = false;
    },
    //删除选项
    deleteOption(options, index) {
      options.splice(index, 1);
    },
    //显示 新增选项输入框
    showOptionInput(row, ref) {
      console.log(row);
      this.$set(row, "visibleNewOptionInput", true);
      // row.visibleNewOptionInput = true;
      this.$nextTick((_) => {
        this.$refs[ref].$refs.input.focus();
      });
    },
    //元素类型切换
    elementChange(row) {
      if (row.valueType == "radio") {
      } else if (row.valueType == "checkbox") {
        row.defalutValue = [];
      }
    },
    //组件类型切换
    componentTypeChange(val) {
      this.templateData.element.column = [];
      this.addCol();
      switch (val) {
        case "0":
          break;
        case "1":
          this.addCol();
          break;
        case "2":
          break;
        default:
          break;
      }
    },
    tableRowClick(row) {
      this.$emit("rowClick", row);
    },
    async getComponentTemplate(val) {
      if (val) {
        this.componentList = await this.$http({
          data: { componentName: val },
          url: "/form/component-template/getComTemplateByName",
        });
      } else {
        this.componentList = await this.$http({
          url: "form/component-template/getComponentTemplate",
        });
      }
    },
  },
  created() {
    this.getComponentTemplate();
  },
};
</script>
<style lang="scss">
#com-list {
  a {
    cursor: pointer;
    color: #409eff;
  }
  .input-new-tag {
    width: 90px;
  }
}
</style>